package com.plian.Tools;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @author kaisong
 */
public class FileTools {
    private static final Logger log = LoggerFactory.getLogger(FileTools.class);

    public static ResponseEntity<FileSystemResource> exportFile(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xlsx");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
                .body(new FileSystemResource(file));
    }

    public static ResponseEntity<FileSystemResource> exportPdf(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "inline; filename=" + System.currentTimeMillis() + ".pdf");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));


        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/pdf;charset=UTF-8"))
                .body(new FileSystemResource(file));

    }


    public static void exportExcel(String filePath, String fileName, HttpServletResponse response) {


        try {
            //取得输出流
            OutputStream os = response.getOutputStream();
            response.reset();//清空输出流
            //下面是对中文文件名的处理
            //设置相应内容的编码格式
            response.setCharacterEncoding("UTF-8");

            InputStream inputStream = new FileInputStream(filePath);
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "UTF-8") + ".xlsx");

            //定义输出类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//			int len;
//			byte[] b = new byte[1024*4];
//			while ((len = inputStream.read(b)) != -1) {
//				os.write(b, 0, len);
//			}
            IOUtils.copy(inputStream, os);

//			response.setHeader("Content-Length", String.valueOf(inputStream.available()));

            inputStream.close();
            os.close();
        } catch (Exception e) {
            log.error(e + "");
        } finally {
            /**
             * 删除文件
             */
            File file = new File(filePath);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        }
    }


    public static ResponseEntity<byte[]> exportExcel(String filePath, String fileName) {
        try {
            HttpHeaders header = new HttpHeaders();
            fileName = fileName + ".xlsx";
            header.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            InputStream is = new FileInputStream(filePath);
            if (is != null && is.available() != 0) {
                header.add("Content-Length", String.valueOf(is.available()));
                header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8"));
                byte[] bs = IOUtils.toByteArray(is);
                return new ResponseEntity<>(bs, header, HttpStatus.OK);
            } else {
                String string = "数据为空";
                header.add("Content-Length", "0");
                header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8"));
                return new ResponseEntity<>(string.getBytes(), header, HttpStatus.OK);
            }
        } catch (Exception e) {
            log.error(e + "");
        } finally {
            /**
             * 删除文件
             */
            File file = new File(filePath);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        }

        return null;
    }
}
